
/* -----------------
* brief 
* 1. this is code gen by tools 
* 2. array like [a,b,c] after each field, define the ui html tag in view, 
		a for title, 
		b for show or not ,  
		c for element html tag , currently suppor : check、radio、select、input、textarea、upload tag
* 3. XXX
*/

package config

import (
	"encoding/json"
	"fmt"
	"github.com/jinzhu/configor"
	"github.com/mjiulee/lego"
	"io/ioutil"
	"path"
	"path/filepath"
	"saas_sys_base/common"
)

type AppConfigModel struct {

}

var __AppConfigMap *common.WhoMap //value类型为AppConfig

func init() {
	model := new(AppConfigModel)
	model.Init() //加载配置
}
//家族配置
func (this *AppConfigModel)Init() {
	__AppConfigMap = common.NewWhoMap()

    appConfigPath := "./config_file"
	files, err := ioutil.ReadDir("./config_file")
	if err != nil {
		return
	}

	for _, f := range files {
		// fmt.Println(f.Name())
		Suffix := path.Ext(f.Name())

		if Suffix == ".yml" {
			filepath := filepath.Join(appConfigPath, f.Name())
        	appConfig := new(common.AppConfig)
			this.LoadConfig(appConfig, filepath)

        	who := common.Who{TenantId:appConfig.Who.Tenant_Id,
        		       MiniAppId:appConfig.Who.Mini_App_Id,
        	           Uid:appConfig.Who.Uid}

			this.UpdateRecode(who, *appConfig)
			//_ = GetAppConfig(who)
		}
	}
}

func (this *AppConfigModel)LoadConfig(Config *common.AppConfig, files string)  {
	err := configor.Load(Config, files)
	if err != nil {
		panic(err)
	}

	_, _ = json.MarshalIndent(&Config, "", "    ")
	//fmt.Printf("###: config start: app_name %s, mini_app_id %d\n", Config.APPName, Config.Who.Mini_App_Id)
	//fmt.Printf("load config: %s\n", configJson)
	fmt.Printf("###: load config: app_name %s, mini_app_id %d\n", Config.APPName, Config.Who.Mini_App_Id)
}

func (this *AppConfigModel)UpdateRecode(who common.Who, config common.AppConfig) {
	__AppConfigMap.SetVal(who, &config)
}

func (this *AppConfigModel)RecodeByWho(who common.Who)  (*common.AppConfig){
	c := __AppConfigMap.GetVal(who)
	if c == nil {
		return nil
	}
	config := __AppConfigMap.GetVal(who).(*common.AppConfig)
	return config
}

func (this *AppConfigModel)ListAll()  ([]*common.AppConfig){
	var arr []*common.AppConfig
	for _, value := range __AppConfigMap.GetMap() {
		v, ok := value.(*common.AppConfig)
		if !ok {
			lego.LogError("AppConfig data error")
		}
		arr = append(arr, v)
	}
	return arr
}
